package com.huanglejing.shanggou.activity

import android.content.ComponentName
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v4.util.ArrayMap
import com.google.gson.JsonObject
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.common.AppBaseActivity
import com.huanglejing.shanggou.interfaces.ConfirmValiContract.ConfirmValiPresenter
import com.huanglejing.shanggou.interfaces.ConfirmValiContract.ConfirmValiView
import com.huanglejing.shanggou.presenterimpl.ConfirmValidImpl
import com.huanglejing.shanggou.rx.SchedulersCompat
import com.huanglejing.shanggou.rx.SimpleSubscriber
import com.huanglejing.shanggou.service.CountDownService
import com.huanglejing.shanggou.utils.*
import com.jakewharton.rxbinding.view.RxView
import kotlinx.android.synthetic.main.activity_confirm_validate.*
import rx.Observable
import java.util.concurrent.TimeUnit


class ConfirmValidateActivity : AppBaseActivity<ConfirmValiPresenter<ConfirmValiView>, ConfirmValiView>(), ConfirmValiView
        , CountDownService.ICountDownCallBack {
    private  var userName=""

    private var binder: CountDownService.CountDownBinder? = null
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            binder = service as CountDownService.CountDownBinder
            binder?.setCountDownListener(this@ConfirmValidateActivity)
            binder?.start(60)
        }

        override fun onServiceDisconnected(name: ComponentName) {

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val phone = intent?.extras?.getString("phone", "")
         userName = intent?.extras?.getString("userName", "")?:""

        tv_confirm_phone?.setHint(phone)
        autoBindService(CountDownService::class.java) { serviceConnection }
        initWidget()
        bindRegister()

    }

    private fun initWidget() {
        setAPPTitle(resources.getString(R.string.str_sms))
        tv_code_time?.text = "${resources.getString(R.string.str_time_to_receive_msg)}60${resources.getString(R.string.str_time_seconds)}"
        tv_code_time?.setOnClickListener {
            if (resources.getString(R.string.str_not_receive_sms).equals(tv_code_time.text.toString())) {
                binder?.start(60)
                bindSend()
            } else {

            }
        }
    }


    private fun bindSend() {
        Observable.just("").throttleFirst(800, TimeUnit.MILLISECONDS)
                ?.flatMap {
                    mBasePresenter.requestValidateNumber(userName)
                }?.compose(SchedulersCompat.io())
                ?.subscribe(object : SimpleSubscriber<JsonObject>() {
                    override fun onError(e: Throwable) {
                        super.onError(e)
                        ToastUtils.toastLong(e?.message)
                        //发送异常，取消计时
                        binder?.stop()
                    }

                    override fun onStart() {
                        super.onStart()
                        ToastUtils.toastLong(resources?.getString(R.string.str_sms_send_success))
                    }

                    override fun onNext(t: JsonObject) {
                        super.onNext(t)
//                        if (t.get("status")?.asString?.equals("00") ?: false) {
//                            ToastUtils.toastLong(resources?.getString(R.string.str_get_sms_success))
//                        }
                    }
                })?.addTo(rxManager)
    }

    private fun bindRegister() {
        RxView.clicks(bt_next_step).throttleFirst(800, TimeUnit.MILLISECONDS)
                .map {
                    et_confirm_code.checkEmpty()
                }
                .subscribe { aBoolean ->
                    if (aBoolean) {
                        ToastUtils.toastLong(resources.getString(R.string.str_please_input_sms))
                    } else {
                        mBasePresenter.confirmCode()
                    }

                }.addTo(rxManager)
    }

    override fun <T> showContent(data: T?) {
        if (data is JsonObject) {
            if (data?.get("status")?.asString?.equals("00") ?: false) {
                ToastUtils.toastLong(data?.get("message")?.asString)
                val bun = Bundle().apply {
                    putString("username", userName)
                    if ("forget".equals(intent?.extras?.getString("type"))){
                        putString("type", "forget")
                    }else{
                        putString("type", "register")
                        putString("yzm", et_confirm_code?.text?.toString())
                    }
                }

                UIHelper.startActivity(SetPwdActivity::class.java,bun)
                finish()
            } else {
                ToastUtils.toastLong(data?.get("message")?.asString)
//                //  TODO  测试代码 需要删除
//                val bun = Bundle().apply {
//                    putString("username", userName)
//                }
//                UIHelper.startActivity(SetPwdActivity::class.java,bun)
//                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(serviceConnection)
    }

    override fun countDown(result: Int) {
        KLog.d()
        if (60 == result) {
            bindSend()
        }
        tv_code_time.text = if (result == 0) {
            resources.getString(R.string.str_not_receive_sms)
        } else {
            "${resources.getString(R.string.str_time_to_receive_msg)}${result}${resources.getString(R.string.str_time_seconds)}"
        }
    }

    override fun finishCountDown() {
        KLog.d()
        tv_code_time?.text = resources.getString(R.string.str_not_receive_sms)
    }

    override fun showError(e: Throwable?) {
        KLog.e(e?.message)
//        //  TODO  测试代码 需要删除
//        val bun = Bundle().apply {
//            putString("username", userName)
//        }
//        UIHelper.startActivity(SetPwdActivity::class.java,bun)
//        finish()
    }

    override fun createPresenter(): ConfirmValiPresenter<ConfirmValiView> = ConfirmValidImpl()

    override fun getLayoutId(): Int = R.layout.activity_confirm_validate

    override fun requestPermission() {
    }


    override fun getRequestParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("username", userName)
            put("yzm",et_confirm_code?.text?.toString() )
        }
        return Observable.just(map)
    }
}
